package com.atguigu.gulimall.product.exception;

import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class gulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerException(MethodArgumentNotValidException e) {

        BindingResult result = e.getBindingResult();

        Map<String, String> map = new HashMap<>();

        result.getFieldErrors().forEach(item -> {
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            map.put(field, defaultMessage);
        });

        return R.error(400, "数据校验异常").put("data", map);

    }

    @ExceptionHandler(value = Exception.class)
    public R handlerException(Exception e){

        return R.error().put("data",e.getMessage());
    }
}
